<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="用户昵称">
          <el-input
            v-model="queryParams.nickname"
            placeholder="请输入用户昵称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select
            v-model="queryParams.paymentStatus"
            placeholder="请选择支付状态"
            clearable
            style="width: 200px"
          >
            <el-option label="全部" :value="null" />
            <el-option label="未支付" :value="0" />
            <el-option label="已支付" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
<!--          <el-button
            type="success"
            @click="handleBatchPay"
            :disabled="!hasUnpaidOrders"
          >
            <template #icon><Money /></template>
            批量支付
          </el-button>-->
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
      >
        <el-table-column key="id" label="ID" prop="id" min-width="80" align="center" />
        <el-table-column key="orderNo" label="订单号" prop="orderNo" min-width="180" align="center" />
        <el-table-column key="userId" label="用户ID" prop="userId" min-width="100" align="center" />
        <el-table-column key="nickname" label="用户昵称" prop="nickname" min-width="120" align="center" />
        <el-table-column key="totalAmount" label="数量" prop="totalAmount" min-width="80" align="center" />
        <el-table-column key="totalMoney" label="金额" prop="totalMoney" min-width="100" align="center">
          <template #default="scope">
            {{ scope.row.totalMoney ? `¥${scope.row.totalMoney}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column key="paymentStatus" label="支付状态" prop="paymentStatus" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.paymentStatus === 1 ? 'success' : 'info'">
              {{ scope.row.paymentStatus === 1 ? '已支付' : '未支付' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column key="orderStatus" label="订单状态" prop="orderStatus" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="getOrderStatusType(scope.row.orderStatus)">
              {{ getOrderStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column key="auditStatus" label="审核状态" prop="auditStatus" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="getAuditStatusType(scope.row.auditStatus)">
              {{ getAuditStatusText(scope.row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="160" align="center" />
        <el-table-column key="updateTime" label="更新时间" prop="updateTime" min-width="160" align="center" />
        <el-table-column key="remark" label="备注" prop="remark" min-width="150" align="center" />
        <el-table-column key="operation" label="操作" min-width="120" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.paymentStatus === 0 && userId === scope.row.userId "
              type="primary"
              size="small"
              :loading="payingOrderId === scope.row.id"
              :disabled="payingOrderId !== null"
              @click="handlePay(scope.row)"
            >
             支付
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 支付方式选择对话框 -->
    <el-dialog v-model="paymentMethodVisible" title="选择支付方式" width="400px">
      <div class="payment-method-select">
        <div class="method-title">请选择支付方式：</div>
        <el-radio-group v-model="selectedPaymentMethod" class="payment-options">
          <el-radio value="wallet">钱包支付</el-radio>
          <el-radio value="offline">线下支付</el-radio>
        </el-radio-group>

        <div class="order-info">
          <div class="info-item">
            <span class="label">订单号：</span>
            <span class="value">{{ currentOrder?.orderNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付金额：</span>
            <span class="value price">¥{{ currentOrder?.totalMoney }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="paymentMethodVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPaymentMethod">确认</el-button>
      </template>
    </el-dialog>

    <!-- 线下支付对话框 -->
    <el-dialog
      v-model="offlinePaymentVisible"
      title="线下支付"
      width="550px"
      @closed="resetOfflinePayment"
    >
      <div class="offline-payment">
        <el-steps :active="paymentStep" finish-status="success" simple class="payment-steps">
          <el-step title="扫码支付" icon="Money" />
          <el-step title="上传凭证" icon="Upload" />
          <el-step title="完成支付" icon="CircleCheck" />
        </el-steps>

        <div class="payment-content">
          <!-- 步骤1: 扫码支付 -->
          <div v-if="paymentStep === 0" class="payment-step-content">
            <div class="qrcode-container">
              <div v-if="loading" class="loading-qrcode">
                <el-skeleton style="width: 200px; height: 200px;" animated />
                <p class="loading-text">正在加载支付二维码...</p>
              </div>
              <div v-else-if="qrcodeData" class="qrcode-content">
                <div class="qrcode-header">
                  <span class="qrcode-title">请选择支付方式并扫描二维码</span>
                </div>
                <div class="payment-methods">
                  <el-radio-group v-model="offlinePaymentMethod" @change="handlePaymentMethodChange">
                    <el-radio label="wx">微信支付</el-radio>
                    <el-radio label="alipay">支付宝支付</el-radio>
                  </el-radio-group>
                </div>
                <div class="qrcode-wrapper">
                  <img :src="currentQrcodeUrl" alt="支付二维码" class="payment-qrcode" />
                </div>
                <div class="qrcode-info">
                  <div class="qrcode-amount">
                    <span class="amount-label">支付金额：</span>
                    <span class="price">¥{{ currentOrder?.totalMoney }}</span>
                  </div>
                  <div class="qrcode-tips">
                    <p>1. 请使用{{ offlinePaymentMethod === 'wx' ? '微信' : '支付宝' }}扫描上方二维码</p>
                    <p>2. 完成支付后请保存付款凭证</p>
                    <p>3. 点击"下一步"上传支付凭证</p>
                  </div>
                </div>
              </div>
              <div v-else class="qrcode-error">
                <el-empty description="二维码加载失败" />
                <el-button type="primary" size="small" @click="getPaymentQrCode">重新加载</el-button>
              </div>
            </div>
          </div>

          <!-- 步骤2: 上传凭证 -->
          <div v-else-if="paymentStep === 1" class="payment-step-content">
            <div class="upload-container">
              <div class="upload-header">
                <div class="upload-title">上传支付凭证</div>
                <div class="upload-subtitle">请上传您的支付截图作为付款凭证</div>
              </div>

              <SingleImageUpload
                v-model="voucherUrl"
                :max-file-size="5"
                :style="{ width: '300px', height: '300px' }"
              />
            </div>
          </div>

          <!-- 步骤3: 确认提交 -->
          <div v-else-if="paymentStep === 2" class="payment-step-content">
            <div class="confirm-container">
              <div class="confirm-header">
                <el-icon class="confirm-icon"><CircleCheckFilled /></el-icon>
                <span class="confirm-title">确认提交</span>
              </div>

              <div class="confirm-content">
                <p class="confirm-text">您已完成支付并上传凭证，请确认以下信息：</p>

                <div class="confirm-info">
                  <div class="confirm-item">
                    <span class="item-label">订单编号：</span>
                    <span class="item-value">{{ currentOrder?.orderNo }}</span>
                  </div>
                  <div class="confirm-item">
                    <span class="item-label">支付金额：</span>
                    <span class="item-value price">¥{{ currentOrder?.totalMoney }}</span>
                  </div>
                  <div class="confirm-item">
                    <span class="item-label">支付方式：</span>
                    <span class="item-value">线下支付</span>
                  </div>
                  <div class="confirm-item">
                    <span class="item-label">凭证状态：</span>
                    <span class="item-value">
                      <el-tag type="success" v-if="voucherUrl">已上传</el-tag>
                      <el-tag type="danger" v-else>未上传</el-tag>
                    </span>
                  </div>
                </div>

                <p class="confirm-note">点击"确认提交"后，系统将记录您的支付信息并等待管理员审核。</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <div class="left-buttons">
            <el-button @click="offlinePaymentVisible = false">取消</el-button>
          </div>
          <div class="right-buttons">
            <el-button v-if="paymentStep > 0" @click="paymentStep--">上一步</el-button>
            <el-button
              v-if="paymentStep < 2"
              type="primary"
              @click="nextStep"
              :disabled="(paymentStep === 0 && !currentQrcodeUrl) || (paymentStep === 1 && !voucherUrl)"
            >
              下一步
            </el-button>
            <el-button
              v-else
              type="success"
              @click="submitOfflinePayment"
              :disabled="!voucherUrl"
            >
              确认提交
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 支付结果对话框 -->
    <el-dialog v-model="resultDialogVisible" :title="paymentSuccess ? '支付成功' : '支付失败'" width="400px">
      <div class="payment-result" :class="{ 'success': paymentSuccess, 'failed': !paymentSuccess }">
        <el-icon :size="48" :color="paymentSuccess ? '#67c23a' : '#f56c6c'">
          <component :is="paymentSuccess ? 'CircleCheckFilled' : 'CircleCloseFilled'" />
        </el-icon>
        <p>{{ paymentSuccess ? resultMessage : errorMessage }}</p>
        <div v-if="paymentSuccess" class="success-info">
          <p>订单编号：{{ currentOrder?.orderNo }}</p>
          <p>支付金额：¥{{ currentOrder?.totalMoney }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="resultDialogVisible = false">关闭</el-button>
        <el-button v-if="!paymentSuccess" type="primary" @click="handleRetry">重试</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import RechargeAPI from "@/api/genealogy/recharge.api";
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Money, Upload, CircleCheck, CircleCheckFilled, CircleCloseFilled } from '@element-plus/icons-vue';
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";

const queryFormRef = ref();
const loading = ref(false);
const total = ref(0);
const payingOrderId = ref(null); // 正在支付的订单ID
import { useUserStore } from "@/store";
const { areaCodeBelong, userId } = useUserStore().userInfo;
// 支付相关状态
const paymentMethodVisible = ref(false);
const offlinePaymentVisible = ref(false);
const resultDialogVisible = ref(false);
const paymentSuccess = ref(false);
const selectedPaymentMethod = ref('wallet');
const currentOrder = ref<any>(null);
const resultMessage = ref('');
const errorMessage = ref('');

// 线下支付相关状态
const voucherUrl = ref('');
const qrcodeData = ref<any>(null);
const offlinePaymentMethod = ref('wx');
const currentQrcodeUrl = ref('');
const paymentStep = ref(0);
const rechargeForm = reactive({
  level: null,
  leadUserId: null
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  nickname: '',
  mobile: '',
  paymentStatus: null, // 新增支付状态筛选参数
});

const pageData = ref([]);

// 计算是否有未支付订单
const hasUnpaidOrders = computed(() => {
  return pageData.value.some(order => order.paymentStatus === 0);
});

function getOrderStatusType(status: number) {
  switch (status) {
    case 0: return 'info';
    case 1: return 'warning';
    case 2: return 'success';
    case 3: return 'danger';
    default: return 'info';
  }
}

function getOrderStatusText(status: number) {
  switch (status) {
    case 0: return '待处理';
    case 1: return '处理中';
    case 2: return '已完成';
    case 3: return '已取消';
    default: return '未知状态';
  }
}

function getAuditStatusType(status: number) {
  switch (status) {
    case 0: return 'warning';
    case 1: return 'success';
    case 2: return 'danger';
    default: return 'info';
  }
}

function getAuditStatusText(status: number) {
  switch (status) {
    case 0: return '待审核';
    case 1: return '已通过';
    case 2: return '已拒绝';
    default: return '无需审核';
  }
}

function handleQuery() {
  loading.value = true;
  RechargeAPI.getMemberOrder(queryParams)
    .then((data: any) => {
      pageData.value = data.list || [];
      total.value = data.total || 0;
    })
    .catch((error: any) => {
      console.error('获取订单数据失败:', error);
      ElMessage.error('获取订单数据失败');
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQuery() {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

function handlePay(row: any) {
  currentOrder.value = row;
  paymentMethodVisible.value = true;
}

// 确认支付方式
function confirmPaymentMethod() {
  if (!currentOrder.value) return;

  paymentMethodVisible.value = false;

  if (selectedPaymentMethod.value === 'offline') {
    // 线下支付
    getPaymentQrCode();
    offlinePaymentVisible.value = true;
  } else {
    // 钱包支付
    processWalletPayment();
  }
}

// 钱包支付处理
function processWalletPayment() {
  if (!currentOrder.value) return;

  payingOrderId.value = currentOrder.value.id;

  RechargeAPI.payOrder(currentOrder.value.id)
    .then((response: any) => {
      paymentSuccess.value = true;
      resultMessage.value = '支付成功！';
      resultDialogVisible.value = true;
      handleQuery(); // 刷新列表
    })
    .catch((error: any) => {
      console.error('支付失败:', error);
      paymentSuccess.value = false;
      errorMessage.value = error.response?.data?.message || '支付失败，请重试';
      resultDialogVisible.value = true;
    })
    .finally(() => {
      payingOrderId.value = null;
    });
}

// 获取支付二维码
function getPaymentQrCode() {
  if (!currentOrder.value) return;

  loading.value = true;
  RechargeAPI.getHighLeader(currentOrder.value.orderNo)
    .then(res => {
      if (res) {
        qrcodeData.value = res;
        rechargeForm.level = res.level;
        rechargeForm.leadUserId = res.leadUserId;
        offlinePaymentMethod.value = 'wx';
        handlePaymentMethodChange();
      } else {
        ElMessage.warning('获取支付二维码失败');
      }
    })
    .catch(error => {
      console.error('获取支付二维码错误:', error);
      ElMessage.error('获取支付二维码失败，请重试');
    })
    .finally(() => {
      loading.value = false;
    });
}

// 切换支付方式
function handlePaymentMethodChange() {
  if (!qrcodeData.value) return;

  if (offlinePaymentMethod.value === 'wx') {
    currentQrcodeUrl.value = qrcodeData.value.receiveMoneyPicWX;
  } else {
    currentQrcodeUrl.value = qrcodeData.value.receiveMoneyPicAliPay;
  }
}

// 下一步
function nextStep() {
  if (paymentStep.value < 2) {
    paymentStep.value++;
  }
}

// 提交线下支付凭证
function submitOfflinePayment() {
  if (!voucherUrl.value || !currentOrder.value) {
    ElMessage.warning('请上传支付凭证');
    return;
  }

  loading.value = true;

  const paymentData = {
    orderNo: currentOrder.value.orderNo,
    paymentMethod: 'offline',
    voucherUrl: voucherUrl.value,
    leadUserId: rechargeForm.leadUserId,
    offPayChannel: offlinePaymentMethod.value === 'wx' ? 0 : 1
  };

  RechargeAPI.ConfirmPurchase(paymentData)
    .then((res: any) => {
      paymentSuccess.value = true;
      resultMessage.value = '您的线下支付凭证已提交，等待管理员审核！';
      resultDialogVisible.value = true;
      handleQuery(); // 刷新列表
    })
    .catch((error) => {
      paymentSuccess.value = false;
      errorMessage.value = error?.response?.data?.msg || '支付凭证提交失败，请重试';
      resultDialogVisible.value = true;
    })
    .finally(() => {
      loading.value = false;
      resetOfflinePayment();
    });
}

// 重置线下支付状态
function resetOfflinePayment() {
  voucherUrl.value = '';
  qrcodeData.value = null;
  currentQrcodeUrl.value = '';
  paymentStep.value = 0;
  offlinePaymentMethod.value = 'wx';
}

// 重试支付
function handleRetry() {
  resultDialogVisible.value = false;
  if (selectedPaymentMethod.value === 'offline') {
    offlinePaymentVisible.value = true;
  } else {
    processWalletPayment();
  }
}

function handleBatchPay() {
  const unpaidOrders = pageData.value.filter(order => order.paymentStatus === 0);
  if (unpaidOrders.length === 0) {
    ElMessage.warning('没有未支付的订单');
    return;
  }

  ElMessageBox.confirm(
    `确认批量支付 ${unpaidOrders.length} 个订单吗？\n请确保所有订单都已审核通过。`,
    '确认批量支付',
    {
      confirmButtonText: '确认支付',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }
  )
    .then(() => {
      const orderIds = unpaidOrders.map(order => order.id);
      payingOrderId.value = orderIds[0]; // 假设批量支付时只支付第一个未支付订单

      // 调用批量支付API
      RechargeAPI.batchPayOrder(orderIds)
        .then((response: any) => {
          ElMessage.success('批量支付成功！');
          handleQuery(); // 刷新列表
        })
        .catch((error: any) => {
          console.error('批量支付失败:', error);
          const errorMsg = error.response?.data?.message || '批量支付失败，请重试';
          ElMessage.error(errorMsg);
        })
        .finally(() => {
          payingOrderId.value = null;
        });
    })
    .catch(() => {
      ElMessage.info('已取消批量支付');
    });
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.app-container {
  padding: 20px;
}

.el-button {
  margin-right: 8px;
}

.el-button:last-child {
  margin-right: 0;
}

.el-table .el-button--small {
  padding: 5px 12px;
  font-size: 12px;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 支付方式选择样式 */
.payment-method-select {
  padding: 20px 0;
}

.method-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.payment-options {
  margin-bottom: 20px;
}

.order-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  margin-top: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  color: #606266;
}

.info-item .value {
  font-weight: bold;
  color: #303133;
}

.info-item .value.price {
  color: #f56c6c;
}

/* 线下支付样式 */
.offline-payment {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.payment-steps {
  margin-bottom: 20px;
  width: 100%;
}

.payment-content {
  padding: 20px;
}

.payment-step-content {
  margin-bottom: 20px;
}

.qrcode-container {
  text-align: center;
  margin-bottom: 20px;
}

.loading-qrcode {
  width: 200px;
  height: 200px;
  margin: 0 auto 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-text {
  text-align: center;
  margin-top: 10px;
  color: #909399;
  width: 100%;
}

.qrcode-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 10px;
}

.qrcode-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.qrcode-title {
  font-weight: bold;
}

.payment-methods {
  margin-bottom: 15px;
  text-align: center;
}

.qrcode-wrapper {
  margin-bottom: 10px;
}

.payment-qrcode {
  width: 200px;
  height: 200px;
  margin-bottom: 10px;
}

.qrcode-info {
  text-align: center;
}

.qrcode-amount {
  font-size: 16px;
  margin: 10px 0;
}

.qrcode-tips {
  color: #606266;
}

.qrcode-tips p {
  margin: 5px 0;
}

.qrcode-error {
  width: 200px;
  height: 200px;
  margin: 0 auto 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.upload-container {
  width: 100%;
  margin-top: 20px;
  padding: 15px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
}

.upload-header {
  margin-bottom: 10px;
}

.upload-title {
  font-weight: bold;
  margin-bottom: 15px;
}

.upload-subtitle {
  color: #606266;
}

.confirm-container {
  text-align: center;
}

.confirm-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.confirm-icon {
  margin-right: 10px;
  color: #67c23a;
}

.confirm-title {
  font-weight: bold;
  font-size: 18px;
}

.confirm-content {
  text-align: left;
}

.confirm-text {
  margin-bottom: 15px;
  color: #303133;
}

.confirm-info {
  margin-bottom: 15px;
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
}

.confirm-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.confirm-item:last-child {
  margin-bottom: 0;
}

.item-label {
  font-weight: bold;
  color: #606266;
}

.item-value {
  color: #303133;
}

.item-value.price {
  color: #f56c6c;
  font-weight: bold;
}

.confirm-note {
  color: #909399;
  font-size: 14px;
  line-height: 1.5;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-buttons {
  display: flex;
  align-items: center;
}

.right-buttons {
  display: flex;
  align-items: center;
}

/* 支付结果样式 */
.payment-result {
  text-align: center;
  padding: 20px 0;
}

.payment-result.success {
  color: #67c23a;
}

.payment-result.failed {
  color: #f56c6c;
}

.success-info {
  margin-top: 15px;
  text-align: left;
  background-color: #f5f7fa;
  padding: 10px 15px;
  border-radius: 4px;
}

.success-info p {
  margin: 5px 0;
  color: #606266;
}
</style>
